import time
from datetime import datetime, timedelta
from . import admin_blu
from app import db, constants
from flask import render_template, request, jsonify, session, redirect, abort, url_for
from app.utils.common import user_login_check
from flask import g, current_app
from app.utils.image_storage import storage
from app.models import Category, News, User
from app.utils.response_code import RET

# 新闻分类编辑
@admin_blu.route('/add_news_category',methods=['POST'])
def add_news_category():
    category_id = request.json.get("id")
    category_name =request.json.get("name")
    if not category_name:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")

    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

        if not category:
            return jsonify(errno=RET.NODATA, errmsg="未查询到分类信息")

        category.name = category_name
    else:
        # 如果没有分类id，则是添加分类
        category = Category()
        category.name = category_name
        db.session.add(category)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    return jsonify(errno=RET.OK, errmsg="保存数据成功")



# 新闻分类
@admin_blu.route('/news_category')
def get_news_category():
    # 获取所有的分类数据
    categories = Category.query.all()
    # 定义列表保存分类数据
    categories_dicts = []

    for category in categories:
        # 获取字典
        cate_dict = category.to_dict()
        # 拼接内容
        categories_dicts.append(cate_dict)

    categories_dicts.pop(0)
    for i in categories_dicts:
        i['id'] -=1
    # 返回内容
    return render_template('admin/news_type.html', data={"categories": categories_dicts})

# 新闻版式编辑详情页
@admin_blu.route('/news_edit_detail', methods=['GET', 'POST'])
def news_edit_detail():
    if request.method == 'GET':
        news_id = request.args.get("news_id")
        if not news_id:
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template("admin/news_edit_detail.html", data={'errmsg': "查询新闻失败"})

        categorises = Category.query.filter(Category.id != 1)
        categorisesList = [i.to_dict() for i in categorises]
        for i in categorisesList:
            i["is_selected"] = (i['id'] == news.category_id)

        return render_template('admin/news_edit_detail.html', data={"news": news.to_dict(),
                                                                    "categories": categorisesList})

    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    if not all([news_id, title, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="七牛云上传失败")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="操作成功")


# 新闻版式编辑
@admin_blu.route('/news_edit')
def news_edit():
    p = request.args.get("p", 1)
    keywords = request.args.get('keywords', "")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    newsEditList = []
    current_page = 1
    total_page = 1

    try:
        filters = []
        if keywords:
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(p, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        newsEditList = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    newsEditList = [i.to_basic_dict() for i in newsEditList]

    data = {"news_edit_list": newsEditList,
            "total_page": total_page,
            "current_page": current_page}
    return render_template('admin/news_edit.html', data=data)


# 新闻审核详情
@admin_blu.route('/news_review_detail', methods=['GET', 'POST'])
def news_review_detail():
    if request.method == 'GET':
        news_id = request.args.get("news_id")
        if not news_id:
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template("admin/news_review_detail.html", data={'errmsg': "查询新闻失败"})

        return render_template('admin/news_review_detail.html', data={"news": news.to_dict()})

    news_id = request.json.get("news_id")
    action = request.json.get("action")

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if action not in ('accept', 'reject'):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查询到数据")

    if action == 'accept':
        news.status = 0
    else:
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        news.reason = reason
        news.status = -1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="操作成功")


# 新闻审核列表
@admin_blu.route('/news_review')
def news_review():
    p = request.args.get("p", 1)
    keywords = request.args.get('keywords', "")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    newsReviewList = []
    current_page = 1
    total_page = 1

    try:
        filters = [News.status != 0]
        if keywords:
            filters.append(News.title.contains(keywords))
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(p, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        newsReviewList = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    newsReviewList = [i.to_review_dict() for i in newsReviewList]

    data = {"news_review_list": newsReviewList,
            "total_page": total_page,
            "current_page": current_page}
    return render_template('admin/news_review.html', data=data)


# 用户列表
@admin_blu.route('/user_list')
def user_list():
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    userList = []
    current_page = 1
    total_page = 1

    try:
        paginate = User.query.filter(User.is_admin == 0).paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        userList = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    userList = [i.to_admin_dict() for i in userList]

    data = {"users_list": userList, "total_page": total_page, "current_page": current_page}
    return render_template('admin/user_list.html', data=data)


# 用户统计
@admin_blu.route('/count', methods=['POST', 'GET'])
@user_login_check
def count():
    totalCount = 0
    # 总人数
    try:
        totalCount = User.query.filter(User.is_admin == 0).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询月新增人数
    monCount = 0

    try:
        now = time.localtime()
        monBegin = "%d-%02d-01" % (now.tm_year, now.tm_mon)
        monBeginDate = datetime.strptime(monBegin, "%Y-%m-%d")
        monCount = User.query.filter(User.create_time >= monBeginDate, User.is_admin == 0).count()

    except Exception as e:
        current_app.logger.error(e)

    dayCount = 0
    try:
        dayBegin = "%d-%02d-%02d" % (now.tm_year, now.tm_mon, now.tm_mday)
        dayBeginDate = datetime.strptime(dayBegin, "%Y-%m-%d")
        dayCount = User.query.filter(User.create_time >= dayBeginDate, User.is_admin == 0).count()

    except Exception as e:
        current_app.logger.error(e)

    nowDate = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')

    activeDate = []
    activeCount = []

    for i in range(0, 31):
        beginDate = (nowDate - timedelta(days=i)).strftime("%Y-%m-%d")
        endDate = (nowDate - timedelta(days=(i - 1))).strftime("%Y-%m-%d")
        activeDate.append(beginDate)
        count = 0
        try:
            count = User.query.filter(User.last_login >= beginDate, User.last_login < endDate,
                                      User.is_admin == 0).count()
        except Exception as e:
            current_app.logger.error(e)

        activeCount.append(count)

    activeCount.reverse()
    activeDate.reverse()

    return render_template('admin/user_count.html',
                           data={
                               "totalCount": totalCount,
                               "monCount": monCount,
                               "dayCount": dayCount,
                               "activeCount": activeCount,
                               "activeDate": activeDate,
                           })


# 后台主页
@admin_blu.route('/index', methods=['POST', 'GET'])
@user_login_check
def admin_index():
    user = g.user
    return render_template('admin/index.html',
                           data={
                               "user_info": user.to_dict() if user else ''
                           })


# 后台登陆页面
@admin_blu.route('/login', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'GET':
        user_id = session.get("user_id", None)
        is_admin = session.get("is_admin", False)
        # 如果用户id存在，并且是管理员，那么直接跳转管理后台主页
        if user_id and is_admin:
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/login.html', errmsg='')

    # 取到登录的参数
    username = request.form.get("username")
    password = request.form.get("password")
    if not all([username, password]):
        return render_template('admin/login.html', errmsg="参数不足")

    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg="数据查询失败")

    if not user:
        return render_template('admin/login.html', errmsg="用户不存在")

    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg="密码错误")

    if not user.is_admin:
        return render_template('admin/login.html', errmsg="用户权限错误")

    session["userid"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = (user.is_admin == 1)

    return redirect(url_for('admin.admin_index'))
